<template>
  <el-container class="home-container">
    <!-- 头部 -->
    <el-header>
      <HeaderComponent />
    </el-header>

    <!-- 主体 -->
    <el-container>
      <!-- 左侧菜单 -->
      <el-aside width="auto" class="aside">
        <!-- 控制菜单展开/收起的按钮 -->
        <div class="menu-toggle" @click="toggleMenu">
          <i :class="isCollapse ? 'el-icon-arrow-right' : 'el-icon-arrow-left'"></i>
        </div>

        <!-- 菜单 -->
        <el-menu
          default-active="/adminHome/orderList"
          class="side-menu"
          background-color="#304156"
          text-color="#bfcbd9"
          active-text-color="#409EFF"
          :collapse="isCollapse"
          :router="true"
        >
          <!-- 订单管理 -->
          <el-menu-item index="/adminHome/orderList">
            <i class="el-icon-document"></i>
            <span slot="title">订单管理</span>
          </el-menu-item>

          <!-- 账号管理（仅超级管理员可见） -->
          <el-menu-item v-if="isSuperAdmin" index="/adminHome/account">
            <i class="el-icon-s-custom"></i>
            <span slot="title">账号管理</span>
          </el-menu-item>

          <!-- 统计信息 -->
          <el-menu-item index="/adminHome/verificationCode">
            <i class="el-icon-data-analysis"></i>
            <span slot="title">验证码管理</span>
          </el-menu-item>
        </el-menu>
      </el-aside>

      <!-- 右侧内容区域 -->
      <el-main class="main-content">
        <router-view />
      </el-main>
    </el-container>

    <!-- 补充信息弹窗 -->
    <el-dialog
      title="请完善个人信息"
      :visible.sync="showUpdateDialog"
      :close-on-click-modal="false"
      :width="isMobile ? '90%' : '400px'"
      @closed="onUpdateDialogClosed"
    >
      <el-form label-position="top" label-width="80px">
        <el-form-item label="手机号">
          <el-input v-model="user.phone" placeholder="请输入手机号" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitUserInfo">提交</el-button>
      </div>
    </el-dialog>

    <!-- 账号激活弹窗 -->
    <el-dialog
      title="请激活账号"
      :visible.sync="showVerifyDialog"
      :close-on-click-modal="false"
      :show-close="false"
      :width="isMobile ? '90%' : '400px'"
    >
      <p>您需要输入验证码来激活账号，验证码请咨询官方</p>
      <p>如果您注册的是超级用户，希望您退出后重新登录</p>
      <br>
      <el-input v-model="verifyCode" placeholder="请输入验证码" />
      <div slot="footer">
        <el-button type="primary" @click="submitVerifyCode">提交</el-button>
        <el-button type="primary" @click="logout">退出</el-button>
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
import HeaderComponent from '@/components/HeaderComponent.vue';
import { mapState, mapMutations } from 'vuex';
import axios from 'axios';

export default {
  components: {
    HeaderComponent,
  },
  name: 'HomeView',
  data() {
    return {
      isCollapse: false, // 默认展开
      showUpdateDialog: false,
      showVerifyDialog: false,
      verifyCode: '',
      isMobile: window.innerWidth <= 768,
    };
  },
  computed: {
    ...mapState(['user']),
    isAdmin() {
      return ['ADMIN', 'SUPER_ADMIN'].includes(this.user?.role);
    },
    isSuperAdmin() {
      return this.user?.role == 'SUPER_ADMIN';
    }
  },
  methods: {
    ...mapMutations(['setUser']),
    toggleMenu() {
      this.isCollapse = !this.isCollapse;
    },
    async checkLoginStatus() {
      try {
        const response = await axios.get('/api/login/admin/checkLoginStatus');
        if (response.data.code == 1) {
          this.setUser(response.data.data);
          this.checkUserStatus(); // 获取到用户信息后再检查权限
        } else {
          this.handleLogout();
        }
      } catch (error) {
        console.error("There was an error checking login status!", error);
        this.handleLogout();
      }
    },
    handleRoleCheck() {
      if (!this.isAdmin) {
        this.$router.push({ name: 'UserUpload' });
      }
    },
    handleLogout() {
      this.$router.push({ path: '/login' });
    },
    checkUserStatus() {
      if (!this.user.phone) {
        this.showUpdateDialog = true;
      }

      if (!this.user.active) {
        this.showVerifyDialog = true;
      }
    },
    async submitUserInfo() {
      if (!this.user.phone) {
        this.$message.warning('手机号不能为空');
        return;
      }

      try {
        const res = await axios.post('/api/admin/updatePersonalInformationById', this.user);
        if (res.data.code == 1) {
          this.setUser(res.data.data); // 更新 Vuex
          this.showUpdateDialog = false;
          this.checkUserStatus(); // 再次检查是否还有其他弹窗要显示
        } else {
          this.$message.error('更新失败,'+res.data.msg);
        }
      } catch (e) {
        console.error('更新用户信息失败', e);
        this.$message.error('网络错误');
      }
    },
    async submitVerifyCode() {
      if (!this.verifyCode) {
        this.$message.warning('请输入验证码');
        return;
      }

      try {
        const res = await axios.post('/api/login/admin/verify', { code: this.verifyCode });
        if (res.data.code == 1) {
          const updatedUser = { ...this.user, active: true };
          this.setUser(updatedUser);
          this.showVerifyDialog = false;
        } else {
          this.$message.error("操作失败："+res.data.msg);
        }
      } catch (e) {
        console.error('验证码提交失败', e);
        this.$message.error('网络错误');
      }
    },
    onUpdateDialogClosed() {
      if (!this.user.active) {
        this.showVerifyDialog = true;
      }
    },
    handleResize() {
      this.isMobile = window.innerWidth <= 768;
    },
    logout() {
      axios.get('/api/login/logout').catch(() => {})
      this.$router.push({ path: '/login' })
    },
  },
  mounted() {
    this.checkLoginStatus();
    window.addEventListener('resize', this.handleResize);
  },
  watch: {
    user: {
      deep: true,
      immediate: true,
      handler(newUser) {
        if (newUser && Object.keys(newUser).length > 0) {
          this.checkUserStatus();
        }
      },
    },
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  }
};
</script>

<style scoped>
.home-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

.el-container {
  flex-grow: 1;
  display: flex;
  background-color: #304156;
}

.aside {
  background-color: #304156;
  transition: width 0.3s ease;
  display: flex;
  flex-direction: column;
}

.menu-toggle {
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #263445;
  color: #fff;
  font-size: 18px;
  cursor: pointer;
  border-bottom: 1px solid #2a3747;
}

.menu-toggle:hover {
  background-color: #1f2d3d;
}

.side-menu {
  flex-grow: 1;
  overflow-y: auto;
}

.side-menu:not(.el-menu--collapse) {
  width: 200px;
}

.main-content {
  padding: 2rem;
  background-color: #f5f7fa;
  flex-grow: 1;
  min-width: 1200px;
}
</style>